package no.knowit.eventorama.dataobject;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Event {

	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Key key;

	@Persistent
	private List<Participant> participants = new ArrayList<Participant>();

	@Persistent
	private String title;

	@Persistent
	private User author;

	@Persistent
	private String comment;

	public Event(String title, String comment, User author) {
		super();
		this.author = author;
		this.title = title;
		this.comment = comment;
	}

	public User getAuthor() {
		return author;
	}

	public String getComment() {
		return comment;
	}

	public Key getKey() {
		return key;
	}

	public List<Participant> getParticipants() {
		return participants;
	}

	public String getTitle() {
		return title;
	}

	public void setAuthor(User author) {
		this.author = author;
	}

	public void setComment(String comment) {
		this.comment = comment;
	}

	public void setParticipants(List<Participant> participants) {
		this.participants = participants;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public boolean canBeDeletedByUser(User user) {
		if (author.equals(user)) {
			if (participants.size() == 0) {
				return true;
			} else {
				if (participants.size() == 1) {
					return participants.get(0).getUser().equals(user);
				} else {
					return false;

				}
			}

		}
		return false;
	}

	public boolean isAnyoneAttending() {
		return getParticipants().size() > 0;
	}

	public boolean getCanBeDeletedByCurrentUser() {
		return canBeDeletedByUser(getCurrentUser());
	}

	public boolean userIsParticipant(User user) {
		for (Participant participant : getParticipants()) {
			if (participant.getUser().equals(user)) {
				return true;
			}
		}
		return false;
	}

	public boolean isCurrentUserParticipant() {
		return userIsParticipant(getCurrentUser());
	}

	private User getCurrentUser() {
		User currentUser = UserServiceFactory.getUserService().getCurrentUser();
		return currentUser;
	}
}
